<template>
  <div>
    <el-dialog title="新增账号" :visible="dialogVisible" @close="close">
      <el-form :model="formData" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="账号" prop="loginname" label-width="120px">
          <el-input v-model="formData.loginname"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="username" label-width="120px">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" label-width="120px">
          <el-input v-model="formData.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="120px">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { checkName,addAdmin} from "@/api/admin";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        loginname: "",
        mobile: "",
        email: "",
        username: ""
      },
      rules: {
        loginname: [{ required: true, message: "请输入", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入", trigger: "blur" }],
        email: [{ required: true, message: "请输入", trigger: "blur" }],
        username: [{ required: true, message: "请输入", trigger: "blur" }]
      }
    };
  },
  methods: {
    close() {
      this.$emit("update:dialogVisible", false);
    },
    save() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let d = await checkName({
            name: this.formData.loginname
          });
          if (!d) {
            this.$message({
              message: "账号重复",
              type: "error"
            });
            return;
          }
          let r = await addAdmin(this.formData);
          if (r && r.error == 0) {
            this.$refs["form"].resetFields();
            this.$emit("finish", r);
            this.close();
          } else {
            this.$message({
              message: "出错了",
              type: "error"
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
